﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace eDoc
{
    public partial class emailsupper : System.Web.UI.Page
    {
        private int id = 0;
        private string email = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["email"] != null)
            {
                email = Request.QueryString["email"].ToString();
            }
            if(!IsPostBack)
            {
                BindData();
            }
        }

        private void LoadData()
        {
            DataTable dt = new DataTable();
            dt = BO.Data.Select_Emails();
            repEmailUser.DataSource = dt;
            repEmailUser.DataBind();
        }

        private void BindData()
        {
            if(string.IsNullOrEmpty(email))
            {
                btAdd.Text = "Thêm mới";
                btAdd.Visible = true;
                btDel.Visible = false;
            }
            else
            {
                DataTable dt = new DataTable();
                dt = BO.Data.Select_Emails_by_Email(email);
                if(dt!=null)
                {
                    txtEmail.Enabled = false;
                    txtEmail.Text = dt.Rows[0]["Email"].ToString();
                    hdID.Value = dt.Rows[0]["ID"].ToString();
                }
                btAdd.Text = "Hủy";
                btDel.Visible = true;
            }
            LoadData();
        }

        protected void btAdd_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(email))
            {
                string strEmail = txtEmail.Text.Trim();
                if (string.IsNullOrEmpty(strEmail))
                {
                    lblNote.Text = "Bạn chưa nhập email!";
                }
                else if (strEmail.IndexOf("@") < 0)
                {
                    lblNote.Text = "Bạn nhập sai email!";
                }
                else
                {
                    bool isCompany = false;
                    if (strEmail.IndexOf("@vietnamairlines.com") > 0)
                    {
                        isCompany = true;
                    }
                    BO.Data.Insert_Emails(strEmail, isCompany);
                    lblNote.Text = "Thêm mới email thành công!";
                }
                LoadData();
            }
            else
            {
                Response.Redirect("/emailsupper.aspx");
            }
        }

        protected void btDel_Click(object sender, EventArgs e)
        {
            BO.Data.Delete_Emails(Convert.ToInt32(hdID.Value));
            lblNote.Text = "Xóa email thành công!";
            LoadData();
        }
    }
}